package com.yty.system.oauth.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yty.system.oauth.entity.ProjectInfo;
import com.yty.system.oauth.service.IProjectInfoService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.sql.Ref;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yegang
 * @since 2023-03-24
 */
@Slf4j
@RestController
@RequestMapping("/projectInfo")
public class ProjectInfoController {

    @Autowired
    private IProjectInfoService projectInfoService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @PostMapping("insert")
    public Object insert()  throws Exception{
        projectInfoService.insert();
        return "操作成功";
    }

    @PostMapping("list")
    public Object list()  throws Exception{
        Page<ProjectInfo> page = projectInfoService.page(new Page<>(1, 20), null);
        List<ProjectInfo> list = page.getRecords();
        try {
            BulkRequest bulk = new BulkRequest();
            for (ProjectInfo projectInfo : list) {
                IndexRequest request = new IndexRequest("projectList").id(projectInfo.getId());
                String json = JSONObject.toJSONString(projectInfo);
                request.source(json, XContentType.JSON);
                bulk.add(request);
            }
            restHighLevelClient.bulk(bulk, RequestOptions.DEFAULT);
            System.out.println("操作成功");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return R.ok("操作成功");
    }

    @GetMapping("queryById")
    public Object queryById(String id)  throws Exception{
        GetRequest request = new GetRequest("projectList",id);
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        String json = response.getSourceAsString();
        return R.ok(json);
    }
}
